﻿using System;
using System.Collections;
using System.Configuration;
using System.Globalization;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;
public partial class WebUserControl_baocaoxuatnhapton : System.Web.UI.UserControl
{
    static string date = "";
    BCDataCenter.DataAccessLayer.DAL dt;
    static DataSet ds = null;
    string error = "";
    static string user = "";
    static string sitecode = "";
    static string usertyp = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                user = Session["Username"].ToString();
                sitecode = Session["Sitecode"].ToString();
                dt = new BCDataCenter.DataAccessLayer.DAL();
                usertyp = dt.MyExecuteQuerys(ref error, "P_GetUserType", CommandType.StoredProcedure, new SqlParameter("@usernames", user));
                if (usertyp == "ad")
                {
                    int fl = 0;
                    ds = dt.MyExecuteQuery(ref error, "P_GetTTPP1", CommandType.StoredProcedure, new SqlParameter("@flag", fl));
                    if (ds.Tables[0].Rows.Count >= 1)
                    {
                        dr_TTPP.DataSource = ds.Tables[0];
                        dr_TTPP.DataValueField = "sitecode";
                        dr_TTPP.DataTextField = "sitename";
                        dr_TTPP.DataBind();
                    }
                    Label4.Visible = false;
                }
                else
                {
                    DataSet dss = new DataSet();
                    dss = dt.MyExecuteQuery(ref error, "P_GetTTPP", CommandType.StoredProcedure, new SqlParameter("@sitecode", sitecode));
                    Label4.Text = dss.Tables[0].Rows[0]["TTPP"].ToString();
                    dr_TTPP.Visible = false;
                }
            }
            catch (Exception ex)
            {
                BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
                string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
                obj.ErrorLog(ex.Message, method);
            }
        }
        else
            try
            {
                ASPxPivotGrid1.DataSource = ds.Tables[0];
                ASPxPivotGrid1.DataBind();
            }
            catch
            {

                return;
            }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
       
        if (txt_tungay.Text == "" || txt_denngay.Text == "")
        {
            uscMsgBox1.AddMessage("Phải chọn ngày", uscMsgBox.enmMessageType.Error);
        }
        else
        {
            if(usertyp=="ad")
                 sitecode = dr_TTPP.SelectedValue.ToString();
            date = txt_tungay.Text.ToString();
            DateTime dateTest = DateTime.Parse(date, new CultureInfo("fr-FR", false));
            DateTime dateTest1 = DateTime.Parse(txt_denngay.Text.ToString(), new CultureInfo("fr-FR", false));
            if (dateTest > dateTest1)
            {
                uscMsgBox1.AddMessage("Vui lòng chọn lại ngày chính xác", uscMsgBox.enmMessageType.Error);
            }
            else
            {
                dateTest = dateTest.AddDays(double.Parse("-1"));
                string tmp = dateTest.ToString("dd/MM/yyyy");
                string monthyeare = tmp.Substring(3, 2) + tmp.Substring(6, 4);
                string monthyeare1 = txt_denngay.Text.ToString().Substring(3, 2) + txt_denngay.Text.ToString().Substring(6, 4);
                dt = new BCDataCenter.DataAccessLayer.DAL();
                bool kq = dt.MyExecuteNonQuery("P_createTMPDIN", CommandType.StoredProcedure, ref error, new SqlParameter("@username", user));
                if (kq)
                {
                    dt.MyExecuteNonQuery("P_insertbeginonhand", CommandType.StoredProcedure, ref error, new SqlParameter("@username", user), new SqlParameter("@todate", txt_denngay.Text.ToString()), new SqlParameter("@date", tmp), new SqlParameter("@sitecode", sitecode), new SqlParameter("@tablename", String.Format("DIN{0}", monthyeare)), new SqlParameter("@tablename1", String.Format("DIN{0}", monthyeare1)));
                    dt.MyExecuteNonQuery("P_insertonhand", CommandType.StoredProcedure, ref error, new SqlParameter("@username", user), new SqlParameter("@todate", txt_denngay.Text.ToString()), new SqlParameter("@date", tmp), new SqlParameter("@sitecode", sitecode), new SqlParameter("@tablename", String.Format("DIN{0}", monthyeare)), new SqlParameter("@tablename1", String.Format("DIN{0}", monthyeare1)));
                    int frommonth = int.Parse(txt_tungay.Text.ToString().Substring(3, 2));
                    int tomonth = int.Parse(txt_denngay.Text.ToString().Substring(3, 2));
                    int fromyear = int.Parse(txt_tungay.Text.ToString().Substring(6, 4));
                    int toyear = int.Parse(txt_denngay.Text.ToString().Substring(6, 4));
                    float iMin = fromyear * 12 + frommonth;
                    float iMax = toyear * 12 + tomonth;
                    float iM = frommonth;
                    float iY = fromyear;
                    while(iMin<=iMax)
                    {
                        int flag = 0;
                        string tablename = "";
                        if (iM < 9)
                            tablename = "DIN0" + iM.ToString() + iY;
                        else
                            tablename = "DIN" + iM.ToString() + iY;
                        if (iM == frommonth && iY==fromyear)
                        {
                            if (iM == tomonth && iY ==toyear)
                            {
                                flag = 0;
                                dt.MyExecuteNonQuery("P_XNTinsertDIN1", CommandType.StoredProcedure, ref error, new SqlParameter("@username", user), new SqlParameter("@tablename", tablename), new SqlParameter("@sitecode", sitecode), new SqlParameter("@fromdate", txt_tungay.Text.ToString()), new SqlParameter("@todate", txt_denngay.Text.ToString()));
                            }
                            else
                            {
                                flag = 1;
                                dt.MyExecuteNonQuery("P_XNTinsertDIN2", CommandType.StoredProcedure, ref error, new SqlParameter("@username", user), new SqlParameter("@tablename", tablename), new SqlParameter("@sitecode", sitecode), new SqlParameter("@fromdate", txt_tungay.Text.ToString()), new SqlParameter("@todate", txt_denngay.Text.ToString()));
                            }
                        }
                        else
                        {
                            if (iM == tomonth && iY ==toyear)
                            {
                                flag = 3;
                                dt.MyExecuteNonQuery("P_XNTinsertDIN4", CommandType.StoredProcedure, ref error, new SqlParameter("@username", user), new SqlParameter("@tablename", tablename), new SqlParameter("@sitecode", sitecode), new SqlParameter("@fromdate", txt_tungay.Text.ToString()), new SqlParameter("@todate", txt_denngay.Text.ToString()));
                            }
                            else
                            {
                                flag = 2;
                                dt.MyExecuteNonQuery("P_XNTinsertDIN3", CommandType.StoredProcedure, ref error, new SqlParameter("@username", user), new SqlParameter("@tablename", tablename), new SqlParameter("@sitecode", sitecode), new SqlParameter("@fromdate", txt_tungay.Text.ToString()), new SqlParameter("@todate", txt_denngay.Text.ToString()));
                            }
                        }
                        iM = iM + 1;
                        if (iM > 12)
                        {
                            iM = 1;
                            iY = iY + 1;
                        }
                        iMin = iY * 12 + iM;
                    }
                    ds = new DataSet();
                    try
                    {
                        dt.MyExecuteNonQuery("P_XNTinsertDIN5", CommandType.StoredProcedure, ref error, new SqlParameter("@username", user));
                        ds = dt.MyExecuteQuery(ref error, "P_getDin", CommandType.StoredProcedure, new SqlParameter("@username", user));
                        if (ds.Tables[0].Rows.Count >= 1)
                        {
                            ASPxPivotGrid1.DataSource = ds.Tables[0];
                            ASPxPivotGrid1.DataBind();
                        }
                        else
                        {
                            ASPxPivotGrid1.DataSource = null;
                            ASPxPivotGrid1.DataBind();
                            uscMsgBox1.AddMessage("không có số liệu trong ngày đã chọn", uscMsgBox.enmMessageType.Error);
                           
                        }
                    }
                    catch (Exception ex)
                    {
                        ASPxPivotGrid1.DataSource = null;
                        ASPxPivotGrid1.DataBind();
                       
                        BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
                        string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
                        obj.ErrorLog(ex.Message, method);
           
                    }
                }
            }
        }
    }
    protected void txt_denngay_TextChanged(object sender, EventArgs e)
    {
        string TTPP = Label4.Text.ToString();
        DateTime dts1,dts;
        if (usertyp == "ad")
            sitecode = dr_TTPP.SelectedValue.ToString();
        if (txt_denngay.Text != "")
        {
            int y = 0;
            string closedated = "";
            dt = new BCDataCenter.DataAccessLayer.DAL();            
            if (sitecode == "0")
            {                
                try
                {
                    dts1 = DateTime.Parse(ds.Tables[0].Rows[0]["closedate"].ToString(), new CultureInfo("fr-FR", false));
                    for (int i = 1; i < ds.Tables[0].Rows.Count; i++)
                    {
                        dts = DateTime.Parse(ds.Tables[0].Rows[i]["closedate"].ToString(), new CultureInfo("fr-FR", false));
                        if (dts > dts1)
                        {
                            dts1 = dts;
                            y = i;
                        }
                    }
                    closedated = ds.Tables[0].Rows[y]["closedate"].ToString();
                    TTPP = ds.Tables[0].Rows[y]["sitename"].ToString();
                }
                catch (Exception ex)
                {
                    BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
                    string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    obj.ErrorLog(ex.Message, method);
                }
            }
            else
            {
                closedated = dt.MyExecuteReaders(ref error, "SELECT [Closed Date] AS closedate FROM mis WHERE (Sitecode = '" + sitecode + "') ", CommandType.Text);
            }
            dts = DateTime.Parse(closedated, new CultureInfo("fr-FR", false));
            dts1 = DateTime.Parse(txt_denngay.Text.ToString(), new CultureInfo("fr-FR", false));
            if (dts < dts1)
            {
                uscMsgBox1.AddMessage("Chọn đến ngày phải <= ngày khóa sổ,ngày khóa sổ cuối cùng là " + closedated + "TTPP " + TTPP , uscMsgBox.enmMessageType.Error);
                txt_denngay.Text = "";
            }
        }
        ASPxPivotGrid1.DataSource = null;
        ASPxPivotGrid1.DataBind();
       
    }
    protected void ASPxButton1_Click(object sender, EventArgs e)
    {
        //using (MemoryStream filestream = new MemoryStream())
        //{
        //    string contentType = "application/ms-excel";
        //    string fileName = "Bao cao Xuat Nhap ton.xls";
        //    ASPxPivotGridExporter1.ExportToXls(filestream);
        //    byte[] buffer = filestream.GetBuffer();
        //    Response.Clear();
        //    Response.Buffer = false;
        //    Response.AppendHeader("Content-Type", contentType);
        //    Response.AppendHeader("Content-Transfer-Encoding", "binary");
        //    Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
        //    Response.BinaryWrite(buffer);
        //    Response.End();
        //}
    }
    protected void Button2_Click(object sender, EventArgs e)
    {

    }
    protected void Button2_Click1(object sender, EventArgs e)
    {
        try
        {
            using (MemoryStream filestream = new MemoryStream())
            {
                string contentType = "application/ms-excel";
                string fileName = "BaocaoXuatNhapton.xls";
                ASPxPivotGridExporter1.ExportToXls(filestream);
                byte[] buffer = filestream.GetBuffer();
                Response.Clear();
                Response.Buffer = false;
                Response.AppendHeader("Content-Type", contentType);
                Response.AppendHeader("Content-Transfer-Encoding", "binary");
                Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
                Response.BinaryWrite(buffer);
                Response.End();
            }
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
    protected void dr_TTPP_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            ASPxPivotGrid1.DataSource = null;
            ASPxPivotGrid1.DataBind();
            txt_tungay.Text = "";
            txt_denngay.Text = "";
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr obj = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            obj.ErrorLog(ex.Message, method);
        }
    }
}
